package com.hccl.controller;

import DM.DialogManager;
import com.hccl.exception.updateException;
import com.hccl.exception.updateFileOperateException;
import com.hccl.service.parser.ParserService;
import com.hccl.mongoEntities.ParserParamEntity;
import entities.SLUResult;
import entities.SysAction;
import gate.Annotation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import com.hccl.mongoEntities.ResultsEntity;

@RestController
@RequestMapping("/nlp")
public class SLUController {

	private static final Logger logger = LoggerFactory.getLogger(SLUController.class);
	@Autowired
	private ParserService parserService;

	// 理解接口
	@RequestMapping(value = "/parser", method = RequestMethod.GET)
	@ResponseBody
	public ResultsEntity parser(@Validated ParserParamEntity parserParam) throws Exception {

		ResultsEntity results = new ResultsEntity();
		if (parserParam.getOffline() != null && parserParam.getOffline().equalsIgnoreCase("true")) {
			parserService.dmReset(parserParam);
		}
		String qurey =  (parserParam.getKeypad()!=null)? parserParam.getKeypad():parserParam.getLine();
		if (qurey==null) qurey="";
		try {
			Map<String,Object> resultMap = parserService.sluParser(parserParam);
			SysAction action = (SysAction) resultMap.get("currentAction");
			ArrayList<SLUResult> sluResults = (ArrayList<SLUResult>) resultMap.get("currentSLU");
			String sluResultStr = "";
			if (sluResults!=null) sluResultStr = sluResults.toString();
			logger.info("\n" + "===================================================" + "\n"
					+ "query: " + qurey + "\n" + "sluResult: "+ sluResultStr + "\n"
					+ "===================================================          " + "\n");
			results.setReply(action.reply);
			results.setUserid(parserParam.getUserid());
			results.setAction(action.stateID);
			results.setParams(action.params);
			results.setInput(qurey);
			results.setFinalSluResult(action.finalSluResult);
			results.setFunction(action.query);
			results.setKeypad(action.keypad);
			if ( parserParam.getDebug() !=null && parserParam.getDebug().trim().toLowerCase().equals("true")) {
				results.setDebug(sluResults);
				results.setGazetteer((Set<Annotation>) resultMap.get("currentGaz"));
			}
		}catch (Exception e) {
			e.printStackTrace();
			if(qurey != null)
				System.out.println(qurey);
		}
		return results;
	}

	// 更新接口
	@RequestMapping(value = "/update", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<Object> update() {
		JSONObject json = new JSONObject();
		String result = "";
		try {
			parserService.backupFiles();
			Boolean updateResult = parserService.update();
			parserService.deleteRecoveryFile();
			result = updateResult ? "更新成功" : "更新失败";
			logger.info("更新成功！");
		}catch (updateFileOperateException e){  //处理文件操作类异常
			result = e.getMessage();
			logger.error("更新失败！请手动恢复lib文件夹，并重启语义理解服务。");
		}catch (updateException e){             //update逻辑类异常，针对update()
			result = e.getMessage();
			try {
				parserService.recovery();
				logger.error("更新失败！但系统配置自动恢复至更新前状态。");
			}catch (updateFileOperateException e1){
				result = e1.getMessage();
				logger.error("更新失败！请手动恢复lib文件夹，并重启语义理解服务。");
			}
		}
		json.put("code", "0");
		json.put("result", result);
		return new ResponseEntity<Object>(json.toString(), HttpStatus.OK);
	}
}
